package controllers;

import java.util.List;

import models.Url;
import models.User;
import models.UserUrls;
import play.Play;
import play.data.binding.As;
import play.data.validation.Error;
import play.data.validation.Required;
import play.mvc.Before;

public class AdminController extends BaseController{
    
    
    @Before
    public static void checkAdmin() {
        String username = session.get("userid");
        User user = User.findCurrentUser(username);
        if (user == null || user.isAdmin == false) {
            AuthorityFilter.login();
        }
    }
    
    public static void listUsers() {
        List<User> users = User.findAll();
        render("/admin/user/list.html", users);
    }
    
    public static void formUser(Long userId) {
        if (userId == null) {
            render("/admin/user/form.html");
        }
        User user = User.findById(userId);
        if (user == null) {
            notFound();
        }
        render("/admin/user/form.html", user);
    }

    public static void saveUser(@Required(message = "user.name.require") String name,@As(value="true") boolean isActive) {
        System.out.println(isActive);
        validationUser(null, name);
        User user = new User();
        user.password = Play.configuration.getProperty("user.defalut.password");
        setUserValue(user, name, isActive).save();
        formUser(user.id);
    }
    
    public static void updateUser(Long userId, @Required(message = "user.name.require") String name, @As(value="true") boolean isActive) {
        validationUser(userId, name);
        User user = User.findById(userId);
        if (user == null) {
            notFound();
        }
        setUserValue(user, name, isActive).save();
        formUser(user.id);
    }
    
    private static User setUserValue(User user, String name, boolean isActive){
        user.name = name.trim();
        user.isActive = isActive;
        return user;
    }
    
    
    private static void validationUser(Long userId, String name) {
        if (validation.hasErrors()) {
            params.flash();
            validation.keep();
            formUser(userId);
        }
        if (isRepeatName(userId, name)) {
            validation.addError("name", "user.name.repeat");
            params.flash();
            validation.keep();
            formUser(userId);
        }
    }
    
    
    private static boolean isRepeatName(Long userId, String name) {
        User exist = User.find("name", name).first();
        if (exist == null) {
            return false;
        }
        if (userId != null && userId.longValue() == exist.id.longValue()) {
            return false;
        }
        return true;
    }
    
    
    public static void resetUser(long userId) {
        User user = User.findById(userId);
        if (user == null) {
            notFound();
        }
        user.password = Play.configuration.getProperty("user.defalut.password");
        user.save();
    }
    
    
    public static void listUrls() {
        List<Url> urls = Url.findAll();
        render("/admin/url/list.html", urls);
    }
    
    public static void formUrl(Long urlId) {
        if (urlId == null) {
            render("/admin/url/form.html");
        }
        
        Url url = Url.findById(urlId);
        if (url == null) {
            notFound();
        }
        render("/admin/url/form.html", url);
    }
    
    private static Url setUrlValue(Url url, String name, String address, Long position) {
        url.name = name;
        url.address = address;
        url.position = position;
        return url;
    }
    
    
    public static void saveUrl(@Required(message = "url.name.require")String name,
                               @Required(message = "url.address.require") String address,
                               Long position) {
        if (validation.hasErrors()) {
            params.flash();
            validation.keep();
            formUrl(null);
        }
        Url url = new Url();
        setUrlValue(url, name, address, position).save();
        formUrl(url.id);
    }
    
    
    public static void updateUrl(Long urlId, 
                                @Required(message = "url.name.require")String name,
                                @Required(message = "url.address.require") String address,
                                Long position) {
        if (validation.hasErrors()) {
            params.flash();
            validation.keep();
            formUrl(urlId);
        }
        if (urlId == null) {
            notFound();
        }
        Url url = Url.findById(urlId);
        setUrlValue(url, name, address, position).save();
        formUrl(url.id);
    }
    
    public static void deleteUrl(long urlId) {
        Url.delete("id", urlId);
        listUrls();
    }
    
    public static void toEditUrlAndUser() {
        List<User> users = User.findAll();
        List<Url> urls = Url.findAll();
        render("/admin/urlanduser/form.html", users, urls);
    }
    
    public static void getSelectdUrls(Long userId) {
        List<UserUrls> userUrls = UserUrls.find("userId", userId).fetch();
        renderJSON(userUrls);
    }

    public static void saveSelectedUrls(Long userId, Long[] selectedUrls) {
        if (userId == null || selectedUrls == null || selectedUrls.length == 0) {
            return;
        }
        UserUrls.delete("userId", userId);
        for (int i = 0; i < selectedUrls.length; i++) {
            UserUrls userUrls = new UserUrls();
            userUrls.urlId = selectedUrls[i];
            userUrls.userId = userId;
            userUrls.save();
        }
        
    }

}